package com.quan.mall.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.quan.common.base.constant.CommonConstant;
import com.quan.common.core.BaseService;
import com.quan.common.utils.RedisOperator;
import com.quan.mall.entity.MallGoodsCategory;
import com.quan.mall.mapper.MallGoodsCategoryMapper;
import com.quan.mall.service.MallGoodsCategoryService;
import com.quan.mall.utils.GoodsCategoryTreeNode;
import com.quan.mall.utils.GoodsCategoryTreeUtil;

import tk.mybatis.mapper.entity.Condition;

/**
 * <p>
 * 电商-商品分类表 服务实现类
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-10-25
 */
@Service
public class MallGoodsCategoryServiceImpl extends BaseService<MallGoodsCategory> implements MallGoodsCategoryService {
	
	@Autowired
	private MallGoodsCategoryMapper mapper ;
	
	@Autowired
	private RedisOperator redisOperator ;
	
	@Override
	public int deleteById(Object id) {
		Condition condition = new Condition(MallGoodsCategory.class) ;
		condition.createCriteria().andEqualTo("pid", id) ;
		List<MallGoodsCategory> childs = this.mapper.selectByCondition(condition) ;
		
		if(null != childs) {
			for (MallGoodsCategory mallGoodsCategory : childs) {
				super.deleteById(mallGoodsCategory.getId());
				delRecursion(mallGoodsCategory);
			}
		} else {
			super.deleteById(id);
		}
		return super.deleteById(id) ;
	}
	
	/**
	 * 递归删除
	 * @param category
	 */
	private void delRecursion(MallGoodsCategory category) {
		Condition condition = new Condition(MallGoodsCategory.class) ;
		condition.createCriteria().andEqualTo("pid", category.getId()) ;
		List<MallGoodsCategory> childs = this.mapper.selectByCondition(condition) ;
		if(null != childs) {
			for (MallGoodsCategory mallGoodsCategory : childs) {
				super.deleteById(mallGoodsCategory.getId());
				delRecursion(mallGoodsCategory);
			}
		} else {
			super.deleteById(category.getId());
		}
	}

	@Override
	public List<Object> treeCategoryAll() {
		
		String categoryTree = this.redisOperator.get(CommonConstant.REDIS_KEY_MALL_CATEGORY) ;
		
		if(null != categoryTree) {
			return JSON.parseArray(categoryTree) ;
		} else {
			Condition condition = new Condition(MallGoodsCategory.class);
	    	condition.setOrderByClause("sort desc");
	    	
	    	List<MallGoodsCategory> list = super.selectAllByCondition(condition);
	    	
	    	List<GoodsCategoryTreeNode> treeNodes = new ArrayList<>();
	    	for (MallGoodsCategory category : list) {
	    		treeNodes.add(new GoodsCategoryTreeNode(category.getId(), category.getPid(), category.getName()));
	    	}
	    	
	    	//将数据进行递归生成tree
	    	List<Object> treeMenu = new GoodsCategoryTreeUtil().treeMenu(treeNodes) ;
	    	this.redisOperator.set(CommonConstant.REDIS_KEY_MALL_CATEGORY, JSON.toJSONString(treeMenu));
	    	return treeMenu ;
		}
		
	}	
}